import React, { useState } from 'react';
import { Upload, Button, message, Image } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { upload } from '@/services/ant-design-pro/api';

const MAX_IMAGES = 3; // Maximum number of images allowed

const ImageUpload = ({ value = [], onChange }) => {
  const [loading, setLoading] = useState(false);

  const handleUpload = async (file) => {
    if (value.length >= MAX_IMAGES) {
      message.error('最多只能上传 3 张图片');
      return false; // Prevent upload
    }

    if (!file.type.startsWith('image/')) {
      message.error('只能上传图片文件');
      return false; // Prevent upload
    }

    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      const response = await upload(formData);
      const newImageUrl = response.data[0]; // 假设返回的是图片的 URL
      onChange([...value, newImageUrl]); // 添加新的图片 URL 到数组中
      message.success('上传成功');
    } catch (error) {
      message.error('上传失败');
    } finally {
      setLoading(false);
    }

    return false; // Prevent automatic upload by Ant Design
  };

  const handleRemove = (index) => {
    const newImages = value.filter((_, i) => i !== index);
    onChange(newImages);
  };

  return (
    <div style={{ marginBottom: 16 }}>
      {value.length > 0 && (
        <div>
          {value.map((imgUrl, index) => (
            <div key={index} style={{ display: 'inline-block', marginRight: 10,marginBottom: 8  }}>
              <Image src={imgUrl} width={100} />
              <Button type="link" onClick={() => handleRemove(index)}>删除</Button>
            </div>
          ))}
        </div>
      )}
      <Upload
        beforeUpload={handleUpload} // Custom upload handler
        fileList={[]}
      >
        <Button icon={<UploadOutlined />} loading={loading}>
          上传图片
        </Button>
      </Upload>
    </div>
  );
};

export default ImageUpload;
